package com.gitee.cui.netty.echoServer;

import com.gitee.cui.netty.NettyDemoConfig;
import com.gitee.cui.util.Logger;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * Netty版本的系统回显服务
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/10/22 15:06
 **/
public class NettyEchoServer {

    private int serverPort;

    private ServerBootstrap bootstrap = new ServerBootstrap();

    public static void main(String[] args) {
        new NettyEchoServer(NettyDemoConfig.SOCKET_SERVER_PORT).runServer();
    }

    NettyEchoServer(int serverPort) {
        this.serverPort = serverPort;
    }

    /**
     * 启动server
     */
    private void runServer() {
        EventLoopGroup boss = new NioEventLoopGroup(1);
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            bootstrap.group(boss, worker);
            bootstrap.channel(NioServerSocketChannel.class);
            bootstrap.localAddress(serverPort);
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(NettyEchoServerHandler.INSTANCE);
                }
            });

            ChannelFuture future = bootstrap.bind().sync();
            Logger.info(" 服务器启动成功，监听端口: " +
                    future.channel().localAddress());
            ChannelFuture closeFuture = future.channel().closeFuture();
            closeFuture.sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
            boss.shutdownGracefully();
        }
    }
}
